﻿using System;
using System.Windows.Media;
using Microsoft.Kinect;
using System.IO;
using System.Windows.Media.Imaging;
using System.Windows;
using System.Runtime.InteropServices;

namespace BodyTrain
{
    public static class ColorExtensions
    {
        #region 定义成员

        //位图资源
        static WriteableBitmap bitmap = null;

        //定义帧宽度
        static int width;

        //定义帧高度
        static int height;

        //RGB像素值
        static byte[] pixels = null;

        #endregion

        #region 定义方法

        public static BitmapSource ToBitmap(this ColorFrame frame)
        {
            if (bitmap == null)
            {
                width = frame.FrameDescription.Width;
                height = frame.FrameDescription.Height;
                pixels = new byte[width * height * Constants.BYTES_PER_PIXEL];
                bitmap = new WriteableBitmap(width, height, Constants.DPI, Constants.DPI, Constants.FORMAT, null);
            }

            if (frame.RawColorImageFormat == ColorImageFormat.Bgra)
            {
                frame.CopyRawFrameDataToArray(pixels);
            }
            else
            {
                frame.CopyConvertedFrameDataToArray(pixels, ColorImageFormat.Bgra);
            }

            bitmap.Lock();

            Marshal.Copy(pixels, 0, bitmap.BackBuffer, pixels.Length);
            bitmap.AddDirtyRect(new Int32Rect(0, 0, width, height));

            bitmap.Unlock();

            return bitmap;
        }
        #endregion
    }
}
